import os
import logging
from pathlib import Path
import pymysql
from app.core.config import settings
from app.core.security import get_password_hash

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

def init_db() -> None:
    try:
        # 连接MySQL（不指定数据库）
        conn = pymysql.connect(
            host=settings.MYSQL_HOST,
            port=settings.MYSQL_PORT,
            user=settings.MYSQL_USER,
            password=settings.MYSQL_PASSWORD,
            charset='utf8mb4'
        )
        
        cursor = conn.cursor()
        
        # 读取SQL文件
        sql_file = Path(__file__).parent / 'init.sql'
        with open(sql_file, 'r', encoding='utf-8') as f:
            sql_commands = f.read()
        
        # 执行SQL命令
        for command in sql_commands.split(';'):
            if command.strip():
                cursor.execute(command)
        
        # 创建初始管理员账号
        admin_password = "admin123"  # 初始密码
        hashed_password = get_password_hash(admin_password)
        
        insert_admin_sql = """
        INSERT INTO perm_system.users (username, email, hashed_password, role, status) 
        VALUES (%s, %s, %s, %s, %s)
        """
        
        try:
            cursor.execute(insert_admin_sql, (
                'admin',
                'admin@example.com',
                hashed_password,
                'admin',
                '启用'
            ))
            logger.info("初始管理员账号创建成功")
        except pymysql.err.IntegrityError:
            logger.info("初始管理员账号已存在，跳过创建")
        
        conn.commit()
        logger.info("数据库初始化完成")
        
    except Exception as e:
        logger.error(f"数据库初始化失败: {str(e)}")
        raise
    finally:
        if 'cursor' in locals():
            cursor.close()
        if 'conn' in locals():
            conn.close()

if __name__ == "__main__":
    logger.info("开始初始化数据库...")
    init_db()
    logger.info("数据库初始化结束") 